package com.xg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xg.common.constant.CommonStatusEnum;
import com.xg.common.response.TokenResponse;
import com.xg.common.result.ApiResult;
import com.xg.common.util.JWTUtils;
import com.xg.common.util.RedisKeyUtils;
import com.xg.entity.User;
import com.xg.mapper.UserMapper;
import com.xg.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xg.util.Md5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author li
 * @since 2023-04-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    //手机号验证
    @Override
    public String queryUserPhone(String userPhone) {
        Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("user_phone", userPhone));
        if (count == 0) {
            // 手机号不存在
            return "0";
        }
        return "1";
    }

    @Override
    public String queryUserEmail(String userEmail) {
        Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("user_email", userEmail));
        if (count == 0) {
            // 邮箱不存在
            return "0";
        }
        return "1";
    }

    @Override
    public User queryUserByName(String username) {
        return userMapper.queryUserByName(username);
    }
    // 查询是否存在用户


    @Override
    public void register(User user) {
        //获取当前时间
        LocalDateTime dateTime = LocalDateTime.now();
        //添加当前时间
        user.setCreateTime(dateTime);
        //加密
        String salt = UUID.randomUUID().toString();
        String md516 = Md5Util.getMd516(user.getUserPassword() + salt);
        String md532 = Md5Util.getMd532(md516);
        //替换原始密码
        user.setUserPassword(md532);
        //把盐保存到数据库
        user.setSalt(salt);
        //把用户保存到数据库
        userMapper.insert(user);
    }


    /**
     * 校验短信验证码
     *
     * @param userPhone
     * @param verificationCode
     */
    @Override
    public ApiResult<TokenResponse> checkVerificationCode(String userPhone, String username, String verificationCode) {

        // 从redis中回去缓存的短信验证码
        if (StringUtils.isBlank(username) || StringUtils.isEmpty(username)){
            username = "";
            String loginKey = RedisKeyUtils.USER_LOGIN_PREFIX+userPhone+"_"+username;

            String code = stringRedisTemplate.opsForValue().get(loginKey);

            if (!org.springframework.util.StringUtils.hasLength(code)){
                return ApiResult.error(CommonStatusEnum.VERIFICATION_CODE_NOT_EXISTS.getCode(),CommonStatusEnum.VERIFICATION_CODE_NOT_EXISTS.getMsg());
            }

            // 校验验证码
            if (!verificationCode.equals(code)){
                return ApiResult.error(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(),CommonStatusEnum.VERIFICATION_CODE_ERROR.getMsg());
            }

            // 通过校验删除缓存中的code
            stringRedisTemplate.delete(loginKey);
        }

        // token
        String accessTokenKey = RedisKeyUtils.ACCESS_TOKEN_PREFIX+userPhone+"_"+username;
        String refreshTokenKey = RedisKeyUtils.REFRESH_TOKEN_PREFIX+userPhone+"_"+username;

        // 生成token
        String accessToken = JWTUtils.genertorToken(userPhone,username);
        String refreshToken = JWTUtils.genertorToken(userPhone,username);

        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,2, TimeUnit.HOURS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken,3, TimeUnit.HOURS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ApiResult.success(tokenResponse);
    }



}

